<?php

define("NOTIFY_MODEL",0);// 0-辽宁  1-南昌
define("EDS_URL","http://172.18.0.131:8082/EDS/jsp/index.jsp");//EDS地址，通过此地址返回的IP进行请求播放地址的拼装
define("PPARAM_URL","EPG/jsp/ipanel/youkulinux/youku.jsp");//用于拼装播放串请求地址的后半段部分
define("IMPORT_IP","10.142.10.174");//用于请求的固定IP地址
define("NTID","00:19:F0:E1:2B:72");//万能MAC地址
define("CARDID","10334482162");//万能智能卡号
define("SUPPORTNET","IP;Cable");//网络类型
define("SERVICE_GROUP_ID","51060");//区域编号

/**
 * 趣享沈阳-CDN反馈验证注入成功or失败
 */
class child_c2_task_notify_model
{
    public $notify_model = 0;
    public $str_sp_id = '';

    public function __construct($sp_id)
    {
        include_once dirname( dirname(dirname(dirname(dirname(__FILE__))))) . '/np/np_http_curl.class.php';
        $this->str_sp_id = $sp_id;
    }

    public function notify_explain($import_id)
    {
        switch (NOTIFY_MODEL)
        {
            case 0:
                nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '趣享辽宁方式', $this->str_sp_id);
                return $this->nx_get_playurl_by_qxsy_huawei($import_id);
                break;
            case 1:
                nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '趣享南昌方式', $this->str_sp_id);
                return $this->nx_get_playurl_by_qxnc_skyworth($import_id);
                break;
        }
    }

    public function nx_get_playurl_by_qxsy_huawei($import_id)
    {
        $curl_1 = new np_http_curl_class();
        $eds_params = sprintf("?User=&pwd=&ip=%s&NTID=%s&CARDID=%s&Version=1.1&lang=1&supportnet=%s&decodemode=H.264;MPEG-2&CA=1&ServiceGroupID=%s&encrypt=0&app_index=jcdb/index.htm",
            IMPORT_IP, NTID, CARDID,SUPPORTNET, SERVICE_GROUP_ID);
        $eds_url = EDS_URL . $eds_params;
        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '置换IP请求地址：'.$eds_url, $this->str_sp_id);
        $eds_result = $curl_1->get($eds_url);
        unset($curl_1);
        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '置换返回：'.var_export($eds_result,true), $this->str_sp_id);
        $eds_result = trim($eds_result);
        // 匹配URL
        preg_match("/http:\/\/.+?\//i", $eds_result, $url_result);
        if (empty($url_result))
        {
            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '未匹配到置换IP，返回注入失败', $this->str_sp_id);
            return false;
        }

        $curl_2 = new np_http_curl_class();
        $request_ip = $url_result[0];
        //$request_ip = 'http://172.18.0.19:33200/';
        // 组装参数
        $base_url = $request_ip . PPARAM_URL;
        $base_url .= "?videoID=" . $import_id;
        $base_url .= "&mac=" . NTID;
        $base_url .= "&ip=" .IMPORT_IP;
        $base_url .= "&icId=" . CARDID;
        $base_url .= "&serviceGroupID=" . SERVICE_GROUP_ID;
        $base_url .= "&businessType=1";
        $base_url .= "&netType=" . SUPPORTNET;
        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '鉴权取串请求地址：'.var_export($base_url,true), $this->str_sp_id);
        $re = $curl_2->get($base_url);
        unset($curl_2);
        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, __FUNCTION__ . '鉴权取串请求返回：'.var_export($re,true), $this->str_sp_id);

        $re = trim($re);
        $result_arr = json_decode($re, true);

        // 返回状态为成功，并且播放串不为空
        if ($result_arr["RETCODE"] == "0" && !empty($result_arr["PLAYURL"]))
        {
            return true;
        }
        // 第三方接口返回需要订购或者其他错误一致返回获取播放串失败。
        else
        {
            return false;
        }
    }

    /**
     * 趣享南昌-CDN反馈验证注入成功or失败
     */
    public function nx_get_playurl_by_qxnc_skyworth($dc, $media, $params, $auth_info, $video_info, $index_info, $ex_data)
    {
        $path = dirname(dirname(dirname(dirname(__FILE__))));
        include_once ($path . '/np/np_http_curl.class.php');
        include_once '../../nn_logic_aaa/common_func.php';

        $request_ip = $_GET['nns_epg_url'];
        if (empty($request_ip))
        {
            // 现在根据EDS接口获取IP地址
            $eds_url = get_config_v2("g_eds_url");
            $log_info = array(
                'errdetail' => "g_eds_url配置为：" . $eds_url
            );
            nl_log_to_syslog::write_info_json_log('1102004000', $log_info);
            if (empty($eds_url))
            {
                return false;
            }

            $params["nns_client_ip"] = np_get_ip();

            $eds_params = sprintf("?User=&pwd=&ip=%s&NTID=%s&CARDID=%s&Version=1.1&lang=1&supportnet=Cable&decodemode=H.264;MPEG-2&CA=1&ServiceGroupID=%s&encrypt=0&app_index=jcdb/index.htm",
                $params["nns_client_ip"], $params["nns_mac_id"], $params["nns_smart_card_id"], $params["nns_service_group_id"]);

            $eds_url .= $eds_params;

            $http_client_x = new np_http_curl_class();
            $eds_result = $http_client_x->get($eds_url);
            $eds_result = trim($eds_result);

            $log_info = array(
                'errdetail' => sprintf(
                    "EDS请求地址：%s, EDS返回：%s",
                    $eds_url,
                    $eds_result
                )
            );
            nl_log_to_syslog::write_info_json_log('1102004000', $log_info);

            // 匹配URL
            preg_match("/http:\/\/.+?\//i", $eds_result, $url_result);
            if (empty($url_result))
            {
                return false;
            }
            $request_ip = $url_result[0];
        }

        $session_id = $_GET['nns_session_id'];
        if (empty($session_id))
        {
            // 先跑一次授权，暂定
            $auth_url = $request_ip . "/EPG/jsp/CheckUser.jsp?User=&pwd=&NTID={$params["nns_mac_id"]}&CARDID={$params["nns_smart_card_id"]}&ServiceGroupID={$params["nns_service_group_id"]}&Version=1.0&lang=1&supportnet=Cable;IP&decodemode=H.264HD;MPEG-2HD&CA=1&encrypt=0&company=1";
            $http_client_one = new np_http_curl_class();
            $http_client_one->response_header = 1;
            $auth_result = $http_client_one->get($auth_url);
            $log_info = array(
                'errdetail' => sprintf(
                    "授权登录请求地址：%s, EDS返回：%s",
                    $auth_url,
                    $auth_result
                )
            );
            nl_log_to_syslog::write_info_json_log('1102004000', $log_info);
            //$auth_result = '{loginStatus:0,message:"login authentication success"}';
            $auth_result = trim($auth_result);

            preg_match("/JSESSIONID=[0-9A-Za-z]+;/i", $auth_result, $session_id_results);
            preg_match("/loginStatus:.*?,/i", $auth_result, $login_status_results);
            $session_id_results = $session_id_results[0];

            $login_status_results = $login_status_results[0];
            $session_id = substr($session_id_results, 0, strlen($session_id_results) - 1);
            $session_id = substr($session_id, 11);
            $login_status = substr($login_status_results, 12, strlen($login_status_results) - 12 - 1);

            if ($login_status != '0')
            {
                $log_info = array(
                    'errdetail' => sprintf(
                        "授权失败"
                    )
                );
                nl_log_to_syslog::write_info_json_log('1102004000', $log_info);
                return false;
            }
        }

        // 先获取配置信息
        $play_url_config = get_config_v2("g_qxnc_skyworth_config");
        $log_info = array(
            'errdetail' => "g_qxnc_skyworth_config配置为：" .var_export($play_url_config, true)
        );
        nl_log_to_syslog::write_info_json_log('1102004000', $log_info);
        if(!is_array($play_url_config))
        {
            $log_info = array(
                'errdetail' => "g_qxnc_skyworth_config，未配置"
            );
            nl_log_to_syslog::write_info_json_log('1102004000', $log_info);
            return false;
        }

        // 组装参数
        $g_qxnc_play_mode = get_config_v2('g_qxnc_play_mode');
        $g_qxnc_play_mode = empty($g_qxnc_play_mode) ? 1 : $g_qxnc_play_mode;
        $base_url = $play_url_config["interface_url"];

        if ($g_qxnc_play_mode == 2)
        {
            $base_url = "EPG/jsp/defaultHD/en/go_Authorization2jx.jsp";
        }

        // 栏目ID 暂定从配置中获取
        $type_id = $params["nns_category_id"];

        // 组装url
        $base_url = $request_ip . '/' . $base_url;

        // playType 播放类型(电影：1电视剧使用11)
        $view_type = $video_info["nns_view_type"];
        // 1表示电视剧
        if ($view_type == 1)
        {
            $playType = "11";
        }
        // 0表示电影
        else if ($view_type == 0)
        {
            $playType = "1";
        }
        // 默认电影
        else
        {
            $playType = "1";
        }

        // progId 资产ID(VODID) 暂定主媒资id
        $prog_id = $media["nns_original_id"];

        // 资产ID
        if ($g_qxnc_play_mode == 2)
        {
            $prog_id = $media['nns_import_id'] . '-youku';
            //$prog_id = '5a3a784116954a22bffbc3ab89a63b03-youku';
        }

        // contentType 内容类型(使用0)
        $content_type = 0;
        // business 无定义 使用1
        $business = 1;
        // baseFlag 无定义 使用0
        $base_flag = 0;

        // get请参数组装
        $get_params = sprintf("?progId=%s&typeId=%s&playType=%s&contentType=%s&business=%s&baseFlag=%s",
            $prog_id, $type_id, $playType, $content_type, $business, $base_flag);

        if ($g_qxnc_play_mode == 2)
        {
            $get_params = sprintf("?progId=%s&typeId=%s&playType=%s&contentType=%s&business=%s&baseFlag=%s&starttime=0&idType=FSN",
                $prog_id, $type_id, $playType, $content_type, $business, $base_flag);
        }

        $log_info = array(
            'errdetail' => "趣享南昌获取播放串参数为：" . var_export($get_params, true)
        );
        nl_log_to_syslog::write_info_json_log('1102004000', $log_info);

        $base_url = $base_url . $get_params;
        $cookie = "JSESSIONID=$session_id";

        $re = send_get_request_and_curl_info($base_url, array(), $cookie);
        $log_info = array(
            'errdetail' => "趣享南昌获取播放串返回结果为：" . var_export($re, true)
        );
        nl_log_to_syslog::write_info_json_log('1102004000', $log_info);

        // 先判断是否走了302跳转
        if ($re['curl_info']['url'] != $base_url)
        {
            return nl_playurl::_result(
                1,
                '',
                'fail',
                1,
                NX_PLAYURL_TYPE_RTSP,
                ''
            );
        }

        $re = trim($re['data']);
        $log_info = array(
            'errdetail' => sprintf(
                "请求地址：%s,cookie为：%s,去趣享南昌获取播放串信息返回：%s",
                $base_url,
                $cookie,
                $re
            )
        );
        nl_log_to_syslog::write_info_json_log('1102004000', $log_info);

        $re = iconv("GBK","UTF-8", $re);

        $log_info = array(
            'errdetail' => sprintf(
                "GBK => UTF8结果为：%s",
                $re
            )
        );
        nl_log_to_syslog::write_info_json_log('1102004000', $log_info);

        preg_match("/playFlag:\"(.+?)\"/i", $re, $playFlag);
        preg_match("/playUrl:\"(.+?)\"/i", $re, $playUrl);

        // 返回状态为成功，并且播放串不为空
        if ($playFlag[1] == "1" && !empty($playUrl[1]))
        {
            $position = strpos($playUrl[1], "rtsp://");
            $play_url = substr($playUrl[1], $position);

            $play_url_arr = explode("^", $play_url);
            $play_url = $play_url_arr[0];
            return nl_playurl::_result(
                0,
                $play_url,
                'success',
                1,
                NX_PLAYURL_TYPE_RTSP,
                ''
            );
        }
        // 第三方接口返回需要订购或者其他错误一致返回获取播放串失败。
        else
        {
            return false;
        }
    }
}